package com.thinkcube.edutainment;

import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.Trace;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.rest.RestService;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ListView;
import android.widget.Toast;

import com.thinkcube.edutainment.adapters.CourseCategoryAdapter;
import com.thinkcube.edutainment.adapters.IndexAdapter;
import com.thinkcube.edutainment.client.CourseClient;
import com.thinkcube.edutainment.client.UserClient;
import com.thinkcube.edutainment.domain.CourseCategory;
import com.thinkcube.edutainment.domain.OAuth;
import com.thinkcube.edutainment.domain.data.CourseCategoryData;
import com.thinkcube.edutainment.domain.dto.CourseDto;
import com.thinkcube.edutainment.domain.dto.OAuthDto;
import com.thinkcube.edutainment.fragment.SearchDetailFragment;
import com.thinkcube.edutainment.fragment.SearchDetailFragment_;

/**
 * A list fragment representing a list of Search. This fragment also supports
 * tablet devices by allowing list items to be given an 'activated' state upon
 * selection. This helps indicate which item is currently being viewed in a
 * {@link SearchDetailFragment}.
 * <p>
 * Activities containing this fragment MUST implement the {@link Callbacks}
 * interface.
 */

@EFragment()
public class SearchListFragment extends Fragment implements
		OnChildClickListener, OnGroupClickListener, OnGroupExpandListener,
		OnGroupCollapseListener, OnItemClickListener {

	@RestService
	CourseClient courseClient;

	@RestService
	UserClient userClient;

	@Bean
	CourseDto courseDto;
	@Bean
	OAuthDto oAuthDto;

	CourseCategoryAdapter cadapter;

	@Background
	void gettoken() {
		oAuthDto.setAppId(EdutainmentConstant.APP_ID);
		oAuthDto.setAppSecret(EdutainmentConstant.APP_SCRET);
		
		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {
				
				try {
					setTokenUi(userClient.getRequestToken(oAuthDto.getMultiValuedMap()));
				} catch (Exception e) {
					
					showMessge(e.getLocalizedMessage());
				}
			}

			@Override
			public void onReachabilityTestFailed() {
				
				showMessge("Not connected ");
			}
		});
		
	}
	
	@UiThread
	void showMessge(final String msg) {
		Toast.makeText(getActivity(), ""
				+msg, Toast.LENGTH_LONG).show();
	}

	void setTokenUi(OAuth requestToken) {

		getCategory(requestToken);
	}

	List<CourseCategoryData> courseCategoryList;
	
	ExpandableListView listview;
	
	ListView filterList;

	IndexAdapter filterAdapter;
	
	ArrayList<String> filters;

	@AfterViews
	void setFilters() {
		filters= new ArrayList<String>();
		filters.add("Featured");
		filters.add("Top Rated");
		filters.add("Latest");
		filters.add("Recommended");

		filterAdapter = new IndexAdapter(getActivity(),
				new String[filters.size()], filters);
		filterAdapter.setSelectedItem(-1);
		filterList.setAdapter(filterAdapter);
		filterList.setOnItemClickListener(this);
		gettoken();

	}

	@Trace
	@Background
	void getCategory(OAuth requestToken) {
		courseDto.setAuthToken(requestToken.getoAuth().getToken());
		
		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {
				
				try {
					doUi(courseClient.getCategory(courseDto.getMultiValuedMap()));
				} catch (Exception e) {
					
					showMessge(e.getLocalizedMessage());
				}
			}

			@Override
			public void onReachabilityTestFailed() {
				
				showMessge("Not connected ");
			}
		});

		
	}

	@UiThread
	void doUi(CourseCategory courseCategory) {
		
		courseCategoryList = courseCategory.getCourseCategoryList();

		listview.setIndicatorBounds(20, 0);
		cadapter = new CourseCategoryAdapter(getActivity(), courseCategoryList);
		listview.setAdapter(cadapter);

		listview.setOnGroupClickListener(this);
		listview.setOnGroupCollapseListener(this);
		listview.setOnGroupExpandListener(this);
		listview.setOnChildClickListener(this);

	}

	/**
	 * The serialization (saved instance state) Bundle key representing the
	 * activated item position. Only used on tablets.
	 */
	private static final String STATE_ACTIVATED_POSITION = "activated_position";

	/**
	 * The fragment's current callback object, which is notified of list item
	 * clicks.
	 */
	private Callbacks mCallbacks = sDummyCallbacks;

	/**
	 * The current activated item position. Only used on tablets.
	 */
	private int mActivatedPosition = ListView.INVALID_POSITION;

	/**
	 * A callback interface that all activities containing this fragment must
	 * implement. This mechanism allows activities to be notified of item
	 * selections.
	 */

	public interface Callbacks {
		/**
		 * Callback for when an item has been selected.
		 */
		public void onItemSelected(String id);
	}

	/**
	 * A dummy implementation of the {@link Callbacks} interface that does
	 * nothing. Used only when this fragment is not attached to an activity.
	 */
	private static Callbacks sDummyCallbacks = new Callbacks() {
		@Override
		public void onItemSelected(String id) {
		}
	};

	/**
	 * Mandatory empty constructor for the fragment manager to instantiate the
	 * fragment (e.g. upon screen orientation changes).
	 */
	public SearchListFragment() {
	}

	DisplayMetrics metrics;
	int width;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater
				.inflate(R.layout.search_side_bar, container, false);
		
		listview = (ExpandableListView) view.findViewById(R.id.list);
		filterList = (ListView) view.findViewById(R.id.listfilter);
		
		metrics = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay()
				.getMetrics(metrics);
		width = metrics.widthPixels;
	
		gettoken();

		return view;
	}

	/*@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		// Restore the previously serialized activated item position.
		if (savedInstanceState != null
				&& savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
					setActivatedPosition(savedInstanceState
							.getInt(STATE_ACTIVATED_POSITION));
		}
	}
*/
	


	@Override
	public void onSaveInstanceState(Bundle outState) {
		
		super.onSaveInstanceState(outState);
		
		if (mActivatedPosition != ListView.INVALID_POSITION) {
			// Serialize and persist the activated item position.
			outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
		}
	}

	/**
	 * Turns on activate-on-click mode. When this mode is on, list items will be
	 * given the 'activated' state when touched.
	 */
	public void setActivateOnItemClick(boolean activateOnItemClick) {
		
		// When setting CHOICE_MODE_SINGLE, ListView will automatically
		// give items the 'activated' state when touched.
		listview.setChoiceMode(activateOnItemClick ? ListView.CHOICE_MODE_SINGLE
				: ListView.CHOICE_MODE_NONE);
	}

	private void setActivatedPosition(int position) {
		
		if (position == ListView.INVALID_POSITION) {
			
			listview.setItemChecked(mActivatedPosition, false);
			
		} else {
			
			listview.setItemChecked(position, true);
			
		}

		mActivatedPosition = position;
	}

	@Override
	public boolean onGroupClick(ExpandableListView parent, View v,
			int groupPosition, long id) {
		
			cadapter.setSelectedGroupItem(groupPosition);
			cadapter.setSelectedChildItem(-1);
			SearchDetailFragment sDetails = new SearchDetailFragment_();
			Bundle bundal = new Bundle();
	
			bundal.putString("category_id", courseCategoryList.get(groupPosition)
					.getCategoryaId());
			sDetails.setArguments(bundal);
			final FragmentTransaction fragmentTransaction = getFragmentManager()
					.beginTransaction();
	
			fragmentTransaction.replace(R.id.search_detail_container1, sDetails,
					"newfrag");
		    fragmentTransaction.addToBackStack(null);
	
			fragmentTransaction.commit();
			
			return false;
	}

	@Override
	public boolean onChildClick(ExpandableListView parent, View v,
			int groupPosition, int childPosition, long id) {
		
			cadapter.setSelectedChildItem(childPosition);
			SearchDetailFragment sDetails = new SearchDetailFragment_();
			Bundle bundal = new Bundle();
	
			bundal.putString("category_id", courseCategoryList.get(groupPosition)
					.getSubCategoryData().get(childPosition).getCategoryaId());
			sDetails.setArguments(bundal);
			final FragmentTransaction fragmentTransaction = getFragmentManager()
					.beginTransaction();
	
			fragmentTransaction.replace(R.id.search_detail_container1, sDetails,
					"newfrag");
			fragmentTransaction.addToBackStack(null);
	
			fragmentTransaction.commit();
			
			return false;
	}

	@Override
	public void onGroupCollapse(int groupPosition) {
		

	}

	private int lastExpandedPosition = -1;

	@Override
	public void onGroupExpand(int groupPosition) {
		
		if (lastExpandedPosition != -1 && groupPosition != lastExpandedPosition) {
			listview.collapseGroup(lastExpandedPosition);
		}
		lastExpandedPosition = groupPosition;

	}

	public int GetDipsFromPixel(float pixels) {
		
		// Get the screen's density scale
		final float scale = getResources().getDisplayMetrics().density;
		// Convert the dps to pixels, based on density scale
		return (int) (pixels * scale + 0.5f);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position,
			long arg3) {
		
			if (filterAdapter != null) {
				filterAdapter.setSelectedItem(position);
			}
			
			
			SearchDetailFragment sDetails = new SearchDetailFragment_();
			Bundle bundal = new Bundle();
	
			bundal.putString("filter", filters.get(position));
			sDetails.setArguments(bundal);
			final FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
	
			fragmentTransaction.replace(R.id.search_detail_container1, sDetails,"newfrag");
			fragmentTransaction.addToBackStack(null);
			fragmentTransaction.commit();

	}

}
